//
//  DHPopController.m
//  DHWeibo
//
//  Created by donghai on 15/12/10.
//  Copyright © 2015年 东海. All rights reserved.
//

#import "DHPopController.h"

@interface DHPopController ()

@property(nonatomic,strong) UIView *contentView;
//遮盖
@property(nonatomic,strong) UIButton *cover;

@property(nonatomic,strong) UIImageView *popView;

@end

@implementation DHPopController

-(instancetype)initWithContentView:(UIView *)contentView
{
    if (self = [super init]) {
        self.contentView = contentView;
        //创建popView
        self.popView = [[UIImageView alloc] init];
        self.popView.userInteractionEnabled = YES;
        //设置imageView背景图片
        UIImage *img = [UIImage imageNamed:@"popover_background"];
        //拉伸图片
        img = [img stretchableImageWithLeftCapWidth:img.size.width * 0.5 topCapHeight:img.size.height * 0.5];
        self.popView.image = img;
        
        CGFloat leftMargin = 10;
        CGFloat rightMargin = 10;
        CGFloat topMargin = 15;
        CGFloat bottomMargin = 10;
        CGFloat popW = self.contentView.w + leftMargin + rightMargin;
        CGFloat popH = self.contentView.h + topMargin + bottomMargin;
        self.popView.size = CGSizeMake(popW, popH);
        //设置contentView x y
        self.contentView.x = leftMargin;
        self.contentView.y = topMargin;
        //把contentView添加到popView
        [self.popView addSubview: self.contentView];
        //初始化遮盖
        self.cover = [[UIButton alloc] init];
        self.cover.bounds = [UIScreen mainScreen].bounds;
        
        [self.cover addTarget:self action:@selector(coverClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return self;
}
#pragma mark 遮盖被点击
-(void)coverClick
{
    //移除遮盖
    [self.cover removeFromSuperview];
    //移除popView
    [self.popView removeFromSuperview];
}
-(void)showInView:(UIView *)inView
{
    //1，显示一个遮盖（在窗口上添加）
    self.cover.x = 0;
    self.cover.y = 0;
    //获得窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.cover];
    //2添加popView.显示popView（往window上）
    CGPoint inViewCenter = inView.center;//实在导航栏上中点
    //设置导航栏中心 转化成窗口的中心点
    CGPoint inViewCenterInWindow = [[inView superview] convertPoint:inView.center toView:nil];
    //2,pop中点往下移
    inViewCenterInWindow.y += self.popView.h * 0.5 + inView.h * 0.5;
    
    self.popView.center = inViewCenterInWindow;
    
    [keyWindow addSubview:self.popView];
    
}

-(void)setAlpha:(CGFloat)alpha
{
    if (alpha > 0) {
        //设置遮盖的透明度
        self.cover.backgroundColor = [UIColor blackColor];
        self.cover.alpha = alpha;
    }
}


-(void)dissmiss
{
    [self coverClick];
}







@end
